from sqlalchemy import Column, String, Integer
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from init.mysql import engine

Base = declarative_base()


class StockHolder(Base):
    __tablename__ = 'stock_holder'
    id = Column(Integer, primary_key=True, autoincrement=True)
    code = Column(String(6))
    jzrq = Column(String(10))
    ggrq = Column(String(10))
    gdsm = Column(String(255))
    gdzs = Column(Integer)
    pjcg = Column(String(20))

    def __init__(self, code, jzrq, ggrq, gdsm, gdzs, pjcg):
        self.code = code
        self.jzrq = jzrq
        self.ggrq = ggrq
        self.gdsm = gdsm
        self.gdzs = gdzs
        self.pjcg = pjcg

    @staticmethod
    def insert_or_update(code, data_list):
        session = sessionmaker(bind=engine)()
        for data in data_list:
            existing_stock_holder = session.query(StockHolder).filter_by(code=code, jzrq=data['jzrq'], ).first()
            if existing_stock_holder:
                existing_stock_holder.ggrq = data['ggrq']
                existing_stock_holder.gdsm = data['gdsm']
                existing_stock_holder.gdzs = data['gdzs']
                existing_stock_holder.pjcg = data['pjcg']
            else:
                session.add(StockHolder(code=code, jzrq=data['jzrq'], ggrq=data['ggrq'],
                                        gdsm=data['gdsm'], gdzs=data['gdzs'], pjcg=data['pjcg']))
        session.commit()


Base.metadata.create_all(engine)
